package app

import (
	"log"
	"net"

	"github.com/dustin/go-coap"
)

func defaultHandle(l *net.UDPConn, a *net.UDPAddr, m *coap.Message) *coap.Message {
	log.Printf("Got message in handleA: path=%q: %s", m.Path(), string(m.Payload))

	if m.IsConfirmable() {
		res := &coap.Message{
			Type:      coap.Acknowledgement,
			Code:      coap.Content,
			MessageID: m.MessageID,
			Token:     m.Token,
			Payload:   []byte("hello to you!"),
		}
		res.SetOption(coap.ContentFormat, coap.TextPlain)

		log.Printf("Transmitting from A %#v", res)
		return res
	}
	return nil
}

func Engine() error {
	mux := coap.NewServeMux()
	mux.Handle("/a", coap.FuncHandler(defaultHandle))
	log.Println("service listen on udp :2001...")
	return coap.ListenAndServe("udp", ":2001", mux)
}
